package com.lap.framework.generator.application.assembler;

import com.lap.framework.common.tool.Named;
import com.lap.framework.generator.configure.EnvConfig;
import com.lap.framework.generator.configure.model.Jdbc;
import com.lap.framework.generator.domain.TemplateModel;
import com.lap.framework.generator.domain.valueobject.FieldModel;
import com.lap.framework.generator.infra.query.meta.ColumnMeta;
import com.lap.framework.generator.infra.query.meta.TableMeta;
import com.lap.framework.generator.shared.tool.TextUtil;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import lombok.experimental.UtilityClass;

@UtilityClass
public class Transformer {

  /**
   * 将表元数据转换为模板模型
   *
   * @param tableMeta 表元数据
   * @param config 环境配置
   * @return 模板模型
   */
  public static TemplateModel transform(TableMeta tableMeta, EnvConfig config) {
    String className = config.getJdbc().getTable().resolveName(tableMeta.getTableName());

    return TemplateModel.builder()
        .author(config.getBaseInfo().getAuthor())
        .version(config.getBaseInfo().getVersion())
        .basePackage(config.getPackName().getBasePackage())
        .tableName(tableMeta.getTableName())
        .tableComment(tableMeta.getTableComment())
        .module(TextUtil.resolveText(className))
        .className(Named.upperHump(className))
        .lowerName(Named.lowerHump(className))
        .mapping(Named.mappingUri(className))
        .fields(resolveFieldModel(Named.lowerHump(className), tableMeta, config))
        .build();
  }

  /**
   * 解析字段模型列表
   *
   * @param parentCode 父级代码（用于关联验证）
   * @param tableMeta 表元数据
   * @param config 环境配置
   * @return 字段模型列表
   */
  private static List<FieldModel> resolveFieldModel(
      String parentCode, TableMeta tableMeta, EnvConfig config) {

    List<FieldModel> fields = new ArrayList<>();
    // 获取配置信息
    Jdbc.TableConfig tableConfig = config.getJdbc().getTable();

    // 创建字段配置对象
    FieldModel.FieldConfig fieldConfig =
        new FieldModel.FieldConfig(
            tableConfig.getExcludeField(),
            tableConfig.getIgnoreInsert(),
            tableConfig.getIgnoreUpdate(),
            tableConfig.getIgnoreCommand());

    // 创建验证上下文
    Set<String> allSet = new HashSet<>();
    allSet.addAll(tableConfig.getExcludeField());
    allSet.addAll(tableConfig.getIgnoreCommand());
    FieldModel.ValidationContext validationContext =
        new FieldModel.ValidationContext(parentCode, allSet);

    for (ColumnMeta column : tableMeta.getColumns()) {
      // 使用工厂方法创建字段模型
      FieldModel fieldModel = FieldModel.createFromColumn(column, fieldConfig, parentCode);

      // 添加验证规则
      fieldModel.addValidations(validationContext);

      fields.add(fieldModel);
    }
    return fields;
  }
}
